import java.sql.Connection;
import java.sql.SQLException;

/**
 * 数据库连接管理类
 */
public class ConnectionManager {
    /**
     * 线程内共享Connection,ThreadLocal通常是全局的，支持泛型
     */
   private static ThreadLocal<Connection> threadLocal = new ThreadLocal();
    public static Connection getCurrConnection(){
        //获取当前线程内共享的Connection
        Connection conn = threadLocal.get();
        try {
            if(conn == null || conn.isClosed()){
                threadLocal.set(conn);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭当前数据库连接
     */
    public static void close(){
        /**
         * 获取当前线程内共享的Connection
         */
        Connection conn = threadLocal.get();
        try {
            if(conn != null && !conn.isClosed()){
                conn.close();
                threadLocal.remove();
                conn = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
